import os
import xlrd
from xlutils.copy import copy
from getBasePath import GetBasePath

xl_top_path = os.path.join(GetBasePath().get_base_path(), 'testCase')


class GetExcelInfo:

    def __init__(self, xl_name, sheet):
        """
        初始化
        :param xl_name:
        :param sheet:
        """
        self.xl_name = xl_name
        self.sheet = sheet
        self.xl_path = os.path.join(xl_top_path, self.xl_name)
        self.read_book = xlrd.open_workbook(self.xl_path)
        self.sheets = self.read_book.sheet_by_name(self.sheet)

    def get_excel_info(self):
        """
        读取Excel，返回所有行信息到一个list
        :return:
        """
        value_list = []
        rows = self.sheets.nrows
        for i in range(rows):
            if i != 0:
                value_list.append(self.sheets.row_values(i))
                print(i, self.sheets.row_values(i))
        return value_list

    def wt_excel_info(self, i, value):
        """

        :param i: 代表插入数据到第几行
        :param value: 代表我们要插入的值
        :return:
        """
        if i != 0:
            write_book = copy(self.read_book)  # 利用xlutils.copy下的copy函数复制
            sheet = write_book.get_sheet(self.sheet)
            sheet.write(i, 3, value)
            write_book.save(self.xl_path)
            return '写入成功！'


if __name__ == '__main__':

    # 插入一条数据，读出来验证读写方法的正确性
    GetExcelInfo('case.xls', 'Sheet1').wt_excel_info(1, 'PASS')
    print(GetExcelInfo('case.xls', 'Sheet1').get_excel_info())
